package com.uranus.auth.auth.service.impl;

import com.uranus.auth.auth.beans.JwtToken;
import com.uranus.auth.auth.beans.User;
import com.uranus.auth.auth.service.JwtService;
import com.uranus.common.VO.TokenUserInfo;
import com.uranus.common.bean.expection.ParamsException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class JwtServiceImpl  implements JwtService{
    @Autowired
    private JwtToken jwtToken;
    @Override
    public TokenUserInfo buildJwtUser(User user) {

        TokenUserInfo tokenUser=new TokenUserInfo();
        tokenUser.setUserId(user.getId());
        tokenUser.setLoginName(user.getLoginName() == null ? "" : user.getLoginName());
        tokenUser.setMobile(user.getMobile() == null ? "" : user.getMobile());
        tokenUser.setNickName(user.getNickName() == null ? "" : user.getNickName());
        tokenUser.setRoleId(user.getRoleId());


        Map<String, Object> map = new HashMap<>();
        map.put("userId", tokenUser.getUserId());
        map.put("loginName", tokenUser.getLoginName());
        map.put("mobile", tokenUser.getMobile());
        map.put("nickName", tokenUser.getNickName());
        map.put("roleId", tokenUser.getRoleId());

        OffsetDateTime nowDateTime = OffsetDateTime.now();
        OffsetDateTime access_token_date = nowDateTime.plusSeconds(jwtToken.getAccessTokenLifetimeSeconds());
        String access_token = buildToken(map, Integer.toString(tokenUser.getUserId()), nowDateTime, access_token_date);
        tokenUser.setAccessToken(access_token);
        tokenUser.setTokenType("bearer");
        return tokenUser;
    }

    private String buildToken(Map<String, Object> map, String userId, OffsetDateTime issuedAt, OffsetDateTime expiration) {
        try {
            return Jwts.builder()
                    .setSubject(userId)
                    .setId(UUID.randomUUID().toString())
                    .setIssuedAt(Date.from(Instant.ofEpochSecond(issuedAt.toEpochSecond())))
                    .setExpiration(Date.from(Instant.ofEpochSecond(expiration.toEpochSecond())))
                    .addClaims(map)
                    .signWith(SignatureAlgorithm.HS512, jwtToken.getJwtSecret().getBytes("UTF-8"))
                    .compact();
        } catch (Exception e) {
            throw new ParamsException("登录token生成失败", e.getMessage());
        }
    }

}
